package org.jeecg.modules.wlhy.hydriver.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ExamineStatusEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.ExcelUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.constant.UserTypeEnum;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.third.digitalseal.utils.ImageBase64Util;
import org.jeecg.modules.third.dongjiang.tax.system.dto.ApiBaseResDTO;
import org.jeecg.modules.third.openapi.OpenApiService;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainDriver;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainVehicle;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainDriverService;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainVehicleService;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hycarrier.entity.HyZhenCarrierOrderDriver;
import org.jeecg.modules.wlhy.hycarrier.service.IHyZhenCarrierOrderDriverService;
import org.jeecg.modules.wlhy.hydriver.entity.*;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriver.vo.HyDriverVehicleVO;
import org.jeecg.modules.wlhy.hydrivercustomer.service.IHyDriverCustomerService;
import org.jeecg.modules.wlhy.hyevent.event.PicDownloadEvent;
import org.jeecg.modules.wlhy.hyplatform.service.IHyPlatformCostService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.hyzhencarrier.entity.HyZhenCarrier;
import org.jeecg.modules.wlhy.hyzhencarrier.service.IHyZhenCarrierService;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.report.IReportService;
import org.jeecg.modules.wlhy.report.OrdosReportService;
import org.jeecg.modules.wlhy.report.ReportServiceFactory;
import org.jeecg.modules.wlhy.report.ShippingNoteApiAlct56Service;
import org.jeecg.modules.wlhy.report.impl.HuaibeiReportService;
import org.jeecg.modules.wlhy.report.impl.YuanqvReportService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.DataMaskingUtil;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 司机管理
 * @Author: duanlikao
 * @Date: 2020-12-02
 * @Version: V1.0
 */
@Api(tags = "司机管理")
@RestController
@RequestMapping("/hydriver/hyDriver")
@Slf4j
public class HyDriverController extends JeecgController<HyDriver, IHyDriverService> {
    @Autowired
    private IHyDriverService hyDriverService;

    @Resource
    private BaseCommonService baseCommonService;
//	@Autowired
//	private IHyWarningMessageService hyWarningMessageService;

    @Autowired
    private IHyDriverVehicleService hyDriverVehicleService;

    @Autowired
    private IHyVehicleService hyVehicleService;

    @Autowired
    private ISysUserService userService;

    @Resource
    private OrdosReportService ordosReportService;

    @Resource
    private HuaibeiReportService huaibeiReportService;

    @Resource
    private YuanqvReportService yuanqvReportService;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private IHyDriverCustomerService hyDriverCustomerService;

    @Autowired
    private IHyCustomerService hyCustomerService;

    @Autowired
    private IHyOrderService hyOrderService;

    @Autowired
    private IHyPlatformCostService hyPlatformCostService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private OpenApiService openApiService;

    @Autowired
    private IHyZhenCarrierOrderDriverService hyZhenCarrierOrderDriverService;

    @Autowired
    private IHyZhenCarrierService hyZhenCarrierService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Resource
    private IHySettingService settingService;

    @Autowired
    private ShippingNoteApiAlct56Service shippingNoteApiAlct56Service;

    @Autowired
    private IHyCompanyConfigService companyConfigService;

   @Autowired
   private IHyCaptainVehicleService carrierDriverService;
    @Autowired
    private IHyCaptainDriverService captainDriverService;
    @Autowired
    private IHyCaptainVehicleService captainVehicleService;
    @Autowired
    private IHyCaptainService captainService;



    @Value(value = "${ysb-daikai.baseUrl:}")
    private String baseUrl;


    /**
     * 分页列表查询
     *
     * @param hyDriver
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "司机管理-分页列表查询", notes = "司机管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HyDriver hyDriver,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HyDriver> queryWrapper = new QueryWrapper<>();
        String driverName = hyDriver.getDriverName();
        if (StringUtils.isNotBlank(driverName)) {
            queryWrapper.like("driver_name", driverName.trim());
            hyDriver.setDriverName("");
        }

        //如果查询上报成功的数据，需要查询任意一个省监管平台
        if (StrUtil.isNotEmpty(hyDriver.getUploadStatus())) {
            queryWrapper.and(wrapper->{
                wrapper.eq("upload_status", hyDriver.getUploadStatus()).or()
                        .eq("sx_upload_status", hyDriver.getUploadStatus()).or()
                        .eq("hb_upload_status", hyDriver.getUploadStatus()).or()
                        .eq("ah_upload_status", hyDriver.getUploadStatus()).or()
                        .eq("js_upload_status", hyDriver.getUploadStatus()).or()
                        .eq("xz_upload_status", hyDriver.getUploadStatus()).or()
                        .eq("zj_upload_status", hyDriver.getUploadStatus()).or()
                        .eq("sd_upload_status", hyDriver.getUploadStatus()).or()
                        .eq("hubei_upload_status", hyDriver.getUploadStatus()).or()
                        .eq("jx_upload_status", hyDriver.getUploadStatus())
                ;
            });

            hyDriver.setUploadStatus("");
        }

        QueryGenerator.initQueryWrapper(queryWrapper, hyDriver, req.getParameterMap());
        Page<HyDriver> page = new Page<HyDriver>(pageNo, pageSize);

        IPage<HyDriver> pageList = hyDriverService.page(page, queryWrapper);
        //如果开启系统脱敏
        String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
        if("1".equals(dataMaskingFlag)) {
            for (HyDriver dto : pageList.getRecords()) {

                dto.setTelephone(DataMaskingUtil.phoneMasking(dto.getTelephone()));
                dto.setIdcard(DataMaskingUtil.idcardMasking(dto.getIdcard()));
                dto.setDrivingLicense(DataMaskingUtil.idcardMasking(dto.getDrivingLicense()));
            }
        }

        return Result.OK(pageList);
    }

    @ApiOperation(value = "司机管理-选择司机控件MMultiSelectDriver.vue专用", notes = "司机管理-选择司机控件MMultiSelectDriver.vue专用")
    @GetMapping(value = "/getSelectDriverList")
    public Result<?> getSelectDriverList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         HttpServletRequest req) {
        String keyword = req.getParameter("keyword");
        if (StringUtils.isBlank(keyword)) {
            return Result.OK(null);
        }
        QueryWrapper<HyDriver> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.del_flag", '0');
        queryWrapper.eq("a.examine_status", ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
        queryWrapper.and(
                qw -> qw.like("a.driver_name", keyword)
                        .or()
                        .like("a.telephone", keyword)
        );
        Page<HySelectDriverDTO> page = new Page<HySelectDriverDTO>(pageNo, pageSize);
//		//是否允许接多单
//		boolean driverMultipleOrders = HyCfgUtil.isUsed2("driver_multiple_orders");
//		if(driverMultipleOrders){
//			IPage<HySelectDriverDTO> pageList = hyDriverService.getMultipleSelectPageList(page, queryWrapper);
//			return Result.OK(pageList);
//		}else{
//			IPage<HySelectDriverDTO> pageList = hyDriverService.getSelectPageList(page, queryWrapper);
//			return Result.OK(pageList);
//		}

        IPage<HySelectDriverDTO> pageList = hyDriverService.getSelectPageList(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param hyDriverDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@RequiresRoles(value={"admin", "customer", "driver"},logical = Logical.OR)
    @ApiOperation(value = "司机管理-分页列表查询", notes = "司机管理-分页列表查询")
    @GetMapping(value = "/newlist")
    public Result<?> queryDriverPageList(HyDriverDTO hyDriverDTO,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<HyDriverDTO> queryWrapper = new QueryWrapper<>();

        HyCustomer customer = userUtil.getCustomer();
        String customerId = "";
        if (customer != null) {
            customerId = customer.getId();
        }
        if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.承运商.getCode())){
            //List<String> driverIdList = userUtil.getDriverList();
            HashSet<String> driverIdList = new HashSet<>();
            //承运商id获取司机id列表
            List<String> list = captainDriverService.list(new LambdaQueryWrapper<HyCaptainDriver>().eq(HyCaptainDriver::getCaptainId, userUtil.getHyCaptain().getId()).select(HyCaptainDriver::getDriverId)).stream().map(HyCaptainDriver::getDriverId).collect(Collectors.toList());
            if (list.size()!=0){
                driverIdList.addAll(list);
            };
            List<String> list1 = userUtil.getDriverList();
            if (list1.size()!=0){
                driverIdList.addAll(list1);
            }
            //获取的司机数据为承运商添加的司机及承运商所属车辆绑定的司机
            if (driverIdList.size()!=0){
                // queryWrapper.in("d.id",userUtil.getDriverList());
                queryWrapper.in("d.id",driverIdList);
            }else {
                return Result.OK();
            }
        }
        if (StringUtils.isNotEmpty(hyDriverDTO.getCarrierName())) {
            //根据承运商姓名获取绑定车辆绑定的司机
            HyCaptain captain = captainService.getOne(new LambdaQueryWrapper<HyCaptain>().like(HyCaptain::getCaptainName, hyDriverDTO.getCarrierName()));
            if (captain==null){
                return Result.OK();
            }
            HashSet<String> driverIdList = new HashSet<>();
            //承运商id获取司机id列表
            List<String> list = captainDriverService.list(new LambdaQueryWrapper<HyCaptainDriver>().eq(HyCaptainDriver::getCaptainId, captain.getId())).stream().map(HyCaptainDriver::getDriverId).collect(Collectors.toList());
            if (list.size()!=0){
                driverIdList.addAll(list);
            };

            List<HyCaptainVehicle> carriers = captainVehicleService.list(new QueryWrapper<HyCaptainVehicle>().eq("captain_id", captain.getId()));
            //根据关联表获取绑定的车辆信息
            List<String> vehicleIdList = carriers.stream().map(HyCaptainVehicle::getVehicleId).collect(Collectors.toList());
            //根据车辆信息获取所绑定的司机信息
            for (String vehicleId : vehicleIdList) {
                driverIdList.addAll(hyDriverVehicleService.getDriverIdListByVehicleId(vehicleId));
            }
            //获取的司机数据为承运商添加的司机及承运商所属车辆绑定的司机
            if (driverIdList.size()!=0){
                // queryWrapper.in("d.id",userUtil.getDriverList());
                queryWrapper.in("d.id",driverIdList);
            }
        }


        queryWrapper.eq("u.`status`", 1);
        queryWrapper.eq("u.`u_type`", "4");

        if (StringUtils.isNotEmpty(hyDriverDTO.getRealname())) {
            queryWrapper.like("u.realname", hyDriverDTO.getRealname());
        }
        if (StringUtils.isNotEmpty(hyDriverDTO.getPhone())) {
            queryWrapper.like("u.phone", hyDriverDTO.getPhone());
        }

        if (StringUtils.isNotEmpty(hyDriverDTO.getUserCreateTime_begin())) {
            queryWrapper.ge("u.create_time", hyDriverDTO.getUserCreateTime_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(hyDriverDTO.getUserCreateTime_end())) {
            queryWrapper.le("u.create_time", hyDriverDTO.getUserCreateTime_end() + " 23:59:59");
        }

        String driverName = hyDriverDTO.getDriverName();
        if (StringUtils.isNotBlank(driverName)) {
            queryWrapper.like("d.driver_name", driverName);
        }
        if (StringUtils.isNotBlank(hyDriverDTO.getTelephone())) {
            queryWrapper.like("d.telephone", hyDriverDTO.getTelephone());
        }
        if (StringUtils.isNotBlank(hyDriverDTO.getIdcard())) {
            queryWrapper.like("d.idcard", hyDriverDTO.getIdcard());
        }
        if (StringUtils.isNotBlank(hyDriverDTO.getExamineStatus())) {
            if (ExamineStatusEnum.EXAMINE_STATUS_TOSUBMITTED.getCode().equals(hyDriverDTO.getExamineStatus())) {
                queryWrapper.isNull("d.id");
            } else {
                queryWrapper.eq("d.examine_status", hyDriverDTO.getExamineStatus());
            }
        }

        if (StringUtils.isNotBlank(hyDriverDTO.getExamineType())) {
            queryWrapper.eq("d.examine_type", hyDriverDTO.getExamineType());
        }


        queryWrapper.orderByDesc("u.create_time");

        Page<HyDriverDTO> page = new Page<HyDriverDTO>(pageNo, pageSize);
        IPage<HyDriverDTO> pageList = hyDriverService.pageList(page, queryWrapper, customerId);
        for (HyDriverDTO dto : pageList.getRecords()) {
           //获取司机绑定的车辆
            List<HyVehicle> vehicleList = hyVehicleService.list(new QueryWrapper<HyVehicle>().eq("driver_id", dto.getId()));
            //根据车辆获取绑定的承运商
            vehicleList.forEach(vehicle -> {
            	HyCaptainVehicle hyCaptainVehicle = captainVehicleService.getOne(new QueryWrapper<HyCaptainVehicle>().eq("vehicle_id", vehicle.getId()));
                if (hyCaptainVehicle!=null){
                    dto.setCarrierId(hyCaptainVehicle.getCaptainId());
                }
            });
        }
        //如果开启系统脱敏
        String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
        if("1".equals(dataMaskingFlag)) {
            for (HyDriverDTO dto : pageList.getRecords()) {
                dto.setPhone(DataMaskingUtil.phoneMasking(dto.getPhone()));
                dto.setTelephone(DataMaskingUtil.phoneMasking(dto.getTelephone()));
                dto.setIdcard(DataMaskingUtil.idcardMasking(dto.getIdcard()));
                dto.setDrivingLicense(DataMaskingUtil.idcardMasking(dto.getDrivingLicense()));
            }
        }

        return Result.OK(pageList);
    }



    @ApiOperation(value = "司机管理-分页列表查询", notes = "司机管理-分页列表查询")
    @GetMapping(value = "/allList")
    public Result<?> allList(@RequestParam(name = "keyword") String keyword, @RequestParam(name = "id", required = false) String id) {
        QueryWrapper<HyDriver> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("examine_status", ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
        if (StringUtils.isEmpty(keyword) && StringUtils.isBlank(id)) {
            return Result.OK(null);
        }
        if (StringUtils.isNotBlank(id)) {
            queryWrapper.eq("id", id);
        } else {
            if (StringUtils.isNotBlank(keyword)) {
                queryWrapper.and(
                        qw -> qw.like("driver_name", keyword)
                                //				.or().like("idcard", keyword)
                                .or().like("telephone", keyword)
                );
            }
        }
        if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.承运商.getCode())){
            HashSet<String> driverIdList = new HashSet<>();
            //承运商id获取司机id列表
            List<String> list = captainDriverService.list(new LambdaQueryWrapper<HyCaptainDriver>().eq(HyCaptainDriver::getCaptainId, userUtil.getHyCaptain().getId()).select(HyCaptainDriver::getDriverId)).stream().map(HyCaptainDriver::getDriverId).collect(Collectors.toList());
            if (list.size()!=0){
                driverIdList.addAll(list);
            };
            List<String> list1 = userUtil.getDriverList();
            if (list1.size()!=0){
                driverIdList.addAll(list1);
            }
            if (driverIdList.size()!=0){
                queryWrapper.in("id",driverIdList);
            }
        }
        List<HyDriver> list = hyDriverService.list(queryWrapper);
        return Result.OK(list);
    }

    @ApiOperation(value = "司机管理-分页列表查询", notes = "司机管理-分页列表查询")
    @GetMapping(value = "/getDriverListBycarrierId")
    public Result<?> getDriverListBycarrierId(@RequestParam(name = "keyword") String keyword) {
        QueryWrapper<HyDriver> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("examine_status", ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
        if (StringUtils.isEmpty(keyword)) {
            return Result.OK(null);
        }
        SysUser user = userUtil.getUser();
        if("5".equals(user.getUType())){
            HyZhenCarrier zhenCarrier = hyZhenCarrierService.getOne(new QueryWrapper<HyZhenCarrier>()
                    .eq("user_id",user.getId())
            );
            if(zhenCarrier!=null){
                List<String> driverIdListByCarrierId = hyZhenCarrierOrderDriverService.getDriverIdListByCarrierId(zhenCarrier.getId());
                queryWrapper.in("id", driverIdListByCarrierId);
            }
        }

        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(
                    qw -> qw.like("driver_name", keyword)
                            //				.or().like("idcard", keyword)
                            .or().like("telephone", keyword)
            );
        }


        List<HyDriver> list = hyDriverService.list(queryWrapper);
        return Result.OK(list);
    }

    @ApiOperation(value = "车辆ID获取司机列表", notes = "车辆ID获取司机列表")
    @GetMapping(value = "/getDriverListByVehicleId")
    public Result<?> getDriverListByVehicleId(@RequestParam(name = "vehicleId") String vehicleId) {
        List<String> driversIds = hyDriverVehicleService.getDriverIdListByVehicleId(vehicleId);
        QueryWrapper<HyDriver> queryDriversWrapper = new QueryWrapper();
        queryDriversWrapper.eq("examine_status", ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
        if (CollectionUtils.isNotEmpty(driversIds)) {
            queryDriversWrapper.in("id", driversIds);
        } else {
            return Result.OK();
        }
        Page<HyDriver> page = new Page<HyDriver>(1, 100);
        IPage<HyDriver> list = hyDriverService.page(page, queryDriversWrapper);
        return Result.OK(list);
    }

    @ApiOperation(value = "承运商ID获取司机列表", notes = "车辆ID获取司机列表")
    @GetMapping(value = "/getDriverListByCarrierId")
    public Result<?> getDriverListByCarrierId(@RequestParam(name = "carrierId") String carrierId) {
        List<String> driverIdListByCarrierId = hyZhenCarrierOrderDriverService.getDriverIdListByCarrierId(carrierId);
        QueryWrapper<HyDriver> queryDriversWrapper = new QueryWrapper();
        if (CollectionUtils.isNotEmpty(driverIdListByCarrierId)) {
            queryDriversWrapper.in("id", driverIdListByCarrierId);
        } else {
            return Result.OK();
        }
        Page<HyDriver> page = new Page<HyDriver>(1, 100);
        IPage<HyDriver> list = hyDriverService.page(page, queryDriversWrapper);
        return Result.OK(list);
    }

    @ApiOperation(value = "删除承运商绑定的司机列表", notes = "删除承运商绑定的司机列表")
    @DeleteMapping(value = "/deleteCarrierDriver")
    public Result<?> deleteCarrierDriver(@RequestParam(name = "carrierId") String carrierId, @RequestParam(name = "driverId") String driverId) {

        if (StrUtil.isEmpty(carrierId) || StrUtil.isEmpty(driverId)) {
            return Result.error("参数错误");
        }

        boolean bDelete = this.hyZhenCarrierOrderDriverService.remove(new LambdaQueryWrapper<HyZhenCarrierOrderDriver>()
                            .eq(HyZhenCarrierOrderDriver::getDriverId, driverId)
                            .eq(HyZhenCarrierOrderDriver::getZhenCarrierId, carrierId));
        if (!bDelete) {
            log.error("删除数据错误，{} {}", carrierId, driverId);
            return Result.error("解除绑定失败");
        }

        return Result.OK("操作成功");
    }


    @ApiOperation(value = "司机ID获取车辆列表", notes = "司机ID获取车辆列表")
    @GetMapping(value = "/getVehicletListByDriverId")
    public Result<?> getVehicletListByDriverId(@RequestParam(name = "driverId") String driverId) {
        List<String> vehicleIds = hyDriverVehicleService.getVehicleIdListByDriverId(driverId);
        if (CollectionUtils.isEmpty(vehicleIds)) {
            return Result.error("您未绑定车辆信息，请先绑定车辆信息！");
        }
        if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.承运商.getCode())){
            vehicleIds = userUtil.getHyVehicleIdList();
        }else {
            vehicleIds = hyDriverVehicleService.getVehicleIdListByDriverId(driverId);
        }
        if (CollectionUtils.isEmpty(vehicleIds)) {
            return Result.error("您未绑定车辆信息，请先绑定车辆信息！");
        }
        QueryWrapper<HyVehicle> queryVehicleWrapper = new QueryWrapper<>();
        queryVehicleWrapper.eq("examine_status", ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
        queryVehicleWrapper.in("id", vehicleIds);
        List<HyVehicle> list = hyVehicleService.list(queryVehicleWrapper);
        return Result.OK(list);
    }


    @ApiOperation(value = "司机管理-分页列表查询", notes = "司机管理-分页列表查询")
    @GetMapping(value = "/getDriverList")
    public Result<?> getDriverList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
//		QueryWrapper<HyDriver> queryWrapper = QueryGenerator.initQueryWrapper(hyDriver, req.getParameterMap());
        QueryWrapper<HyDriverVehicleVO> queryWrapper = new QueryWrapper<>();
        String driverName = req.getParameter("driverName");
        String idcard = req.getParameter("idcard");
        String telephone = req.getParameter("telephone");
        String vehicleNumber = req.getParameter("vehicleNumber");

        if (StringUtils.isEmpty(driverName)
                && StringUtils.isEmpty(idcard)
                && StringUtils.isEmpty(telephone)
                && StringUtils.isEmpty(vehicleNumber)
        ) {
            return Result.error("搜索条件不能同时为空");
        }

        if (StringUtils.isNotEmpty(driverName)) {
            queryWrapper.like("hy_driver.driver_name", driverName);
        }

        if (StringUtils.isNotEmpty(idcard)) {
            queryWrapper.like("hy_driver.idcard", idcard);
        }

        if (StringUtils.isNotEmpty(telephone)) {
            queryWrapper.like("hy_driver.telephone", telephone);
        }

        if (StringUtils.isNotEmpty(vehicleNumber)) {
            queryWrapper.like("hy_vehicle.vehicle_number", vehicleNumber);
        }

        Page<HyDriverVehicleVO> page = new Page<HyDriverVehicleVO>(pageNo, pageSize);
        IPage<HyDriverVehicleVO> pageList = hyDriverService.getDriverVehiclePageList(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hyDriver
     * @return
     */
//	@AutoLog(value = "司机管理-添加")
    @ApiOperation(value = "司机管理-添加", notes = "司机管理-添加")
    @PostMapping(value = "/add")
    @RequiresPermissions("sys:driver:add")
    public Result<?> add(@RequestBody @Valid HyDriver hyDriver) {
        String telephone = hyDriver.getTelephone();
        if (StringUtils.isEmpty(telephone)) {
            return Result.error("手机号不能为空");
        }
        if (StringUtils.isBlank(hyDriver.getIdcard())) {
            throw new JeecgBootException("身份证号不能为空。");
        }
        SysUser sysUser = userService.getUserByPhone(telephone);
        HyDriver queryHoneHyDriver = hyDriverService.getHyDriverByTelephone(telephone);
        if (sysUser != null && queryHoneHyDriver != null) {
            return Result.error("该司机手机号已存在,不能重复注册");
        }

        hyDriver.setUserId(sysUser != null && "4".equals(sysUser.getUType()) ? sysUser.getId() : null);
        hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
        hyDriver.setExamineType("1");
        hyDriver.setExamineDate(new Date());

        //if(StringUtils.isNotBlank(hyDriver.getUserId())){
        //	HyDriver hyDriverDb = hyDriverService.getHyDriverByUserId(hyDriver.getUserId());
        //	if(hyDriverDb != null  ){
        //		return Result.error("用户已经绑定:" +hyDriverDb.getDriverName()+"，请勿重复绑定");
        //	}
        //}
        return hyDriverService.saveHyDriver(hyDriver);
    }

    /**
     * 编辑
     *
     * @param hyDriver
     * @return
     */
    @AutoLog(value = "司机管理-编辑")
    @ApiOperation(value = "司机管理-编辑", notes = "司机管理-编辑")
    @PutMapping(value = "/edit")
    @RequiresPermissions("sys:driver:edit")
    @Transactional
    @CacheEvict(value = CacheConstant.SYS_DICT_TABLE_CACHE, key = "'SimpleKey [hy_driver,driver_name,id,' + #hyDriver.id + ']'")
    public Result<?> edit(@RequestBody @Valid HyDriver hyDriver) {

        String telephone = hyDriver.getTelephone();
        if (StringUtils.isEmpty(telephone)) {
            return Result.error("手机号不能为空");
        }

//		hyDriver.setAreaCode( hyDriver.getIdcard().substring(0 , 6) );

        String id = hyDriver.getId();
        HyDriver old = hyDriverService.getById(id);
        if (old == null) {
            return Result.error("司机信息不存在");
        }

        //如果开启系统脱敏
        String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
        if ("1".equals(dataMaskingFlag)) {
            return Result.error("系统数据已脱敏，不允许编辑司机信息");
        }

        if (!StringUtils.equals(telephone, old.getTelephone())) {
            //修改手机号
            String userId = old.getUserId();
            SysUser user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户信息不存在");
            }
            //检查手机号是否已存在
            List<SysUser> list = userService.list(new QueryWrapper<SysUser>()
                    .eq("phone", telephone)
                    .ne("id", userId));
            if (list.size() > 0) {
                return Result.error("手机号已被占用");
            }
            user.setPhone(telephone);
            userService.updateById(user);
        }

//		if(StringUtils.isBlank(hyDriver.getUserId())){
//			return Result.error("请选择司机所属用户");
//		}
//		if(StringUtils.isNotBlank(hyDriver.getUserId())){
//
//			QueryWrapper<HyDriver> queryWrapper = new QueryWrapper<>();
//			queryWrapper.eq("user_id",hyDriver.getUserId());
//			queryWrapper.ne("id",hyDriver.getId());
//			HyDriver hyDriverDb = hyDriverService.getOne(queryWrapper);
//			if(hyDriverDb != null){
//				return Result.error("用户已经绑定:" +hyDriverDb.getDriverName()+"，请勿重复绑定");
//			}
//		}
        hyDriverService.updateById(hyDriver);
        return Result.OK("编辑成功!");
    }

    //	/**
//	 *   通过id删除
//	 *
//	 * @param id
//	 * @return
//	 */
    @AutoLog(value = "司机管理-通过id删除")
    @ApiOperation(value = "司机管理-通过id删除", notes = "司机管理-通过id删除")
    @DeleteMapping(value = "/delete")
    @RequiresPermissions("sys:driver:delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {

        // hyDriverService.removeById (id);
        HyDriver driver = hyDriverService.getDriverById(id);

        //添加日志
        log.warn("删除司机信息, {}", JSONUtil.toJsonStr(driver));


        //有司机信息
        if (driver != null) {
            QueryWrapper<HyShippingNote> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("driver_id", id);
            //如果是承运商的话只是删除跟司机关联的表数据，不会删除司机
            if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.承运商.getCode())){
                log.info("承运商删除司机,{}",JSONUtil.toJsonStr(driver));
                carrierDriverService.remove(new QueryWrapper<HyCaptainVehicle>().eq("driver_id",id));
                driver.setCarrierId("");
                hyDriverService.updateById(driver);
                List<HyVehicle> vehicles = hyVehicleService.getVehicleByDriverId(id);
                for (HyVehicle vehicle : vehicles) {
                    vehicle.setCarrierId("");
                }
                hyVehicleService.updateBatchById(vehicles);
                return Result.ok();
            }
            int shippingNoteCount = hyShippingNoteService.count(queryWrapper);
            if (shippingNoteCount > 0) {
                return Result.error(driver.getDriverName() + "司机已有业务数据,不允许删除");
            }

            baseCommonService.addLog("删除司机动作1: " + driver.getId() + " " + driver.getDriverName(), CommonConstant.LOG_TYPE_1, null);
            hyDriverService.deleteDriverById(id);
            sysUserService.deleteUser(Arrays.asList(driver.getUserId()));
            hyDriverCustomerService.deleteDriverCustomeByDriverId(id);
            carrierDriverService.remove(new QueryWrapper<HyCaptainVehicle>().eq("driver_id",id));
            return Result.OK("删除成功!");
        } else {
            //有用户没司机
            SysUser user = userService.getById(id);
            if (user == null) {
                return Result.error("用户信息不存在");
            }
            if (!"4".equals(user.getUType())) {
                return Result.error("不是司机用户不能删除");
            }

            baseCommonService.addLog("删除司机动作2: " + JSONUtil.toJsonStr(user), CommonConstant.LOG_TYPE_1, null);
            sysUserService.deleteUser(Arrays.asList(id));
            carrierDriverService.remove(new QueryWrapper<HyCaptainVehicle>().eq("driver_id",id));
            return Result.OK("删除成功!");
        }

    }

//
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "司机管理-批量删除")
//	@ApiOperation(value="司机管理-批量删除", notes="司机管理-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyDriverService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "司机管理-通过id查询", notes = "司机管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HyDriver hyDriver = hyDriverService.getById(id);
        if (hyDriver == null) {
            return Result.error("未找到对应数据");
        }

        //如果开启系统脱敏
        String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
        if("1".equals(dataMaskingFlag)) {
            hyDriver.setTelephone(DataMaskingUtil.phoneMasking(hyDriver.getTelephone()));
            hyDriver.setIdcard(DataMaskingUtil.idcardMasking(hyDriver.getIdcard()));
            hyDriver.setDrivingLicense(DataMaskingUtil.idcardMasking(hyDriver.getDrivingLicense()));
        }

        return Result.OK(hyDriver);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hyDriverDTO
     */
    @RequestMapping(value = "/exportXls")
    @RequiresPermissions("sys:driver:exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HyDriverDTO hyDriverDTO) {

        QueryWrapper<HyDriverDTO> queryWrapper = new QueryWrapper<>();

        HyCustomer customer = userUtil.getCustomer();
        String customerId = "";
        if (customer != null) {
            customerId = customer.getId();
        }

        queryWrapper.eq("u.`status`", 1);
        queryWrapper.eq("u.`u_type`", "4");

        if (StringUtils.isNotEmpty(hyDriverDTO.getRealname())) {
            queryWrapper.like("u.realname", hyDriverDTO.getRealname());
        }
        if (StringUtils.isNotEmpty(hyDriverDTO.getPhone())) {
            queryWrapper.like("u.phone", hyDriverDTO.getPhone());
        }

        if (StringUtils.isNotEmpty(hyDriverDTO.getUserCreateTime_begin())) {
            queryWrapper.ge("u.create_time", hyDriverDTO.getUserCreateTime_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(hyDriverDTO.getUserCreateTime_end())) {
            queryWrapper.le("u.create_time", hyDriverDTO.getUserCreateTime_end() + " 23:59:59");
        }

        String driverName = hyDriverDTO.getDriverName();
        if (StringUtils.isNotBlank(driverName)) {
            queryWrapper.like("d.driver_name", driverName);
        }
        if (StringUtils.isNotBlank(hyDriverDTO.getTelephone())) {
            queryWrapper.like("d.telephone", hyDriverDTO.getTelephone());
        }
        if (StringUtils.isNotBlank(hyDriverDTO.getIdcard())) {
            queryWrapper.like("d.idcard", hyDriverDTO.getIdcard());
        }
        if (StringUtils.isNotBlank(hyDriverDTO.getExamineStatus())) {
            if (ExamineStatusEnum.EXAMINE_STATUS_TOSUBMITTED.getCode().equals(hyDriverDTO.getExamineStatus())) {
                queryWrapper.isNull("d.id");
            } else {
                queryWrapper.eq("d.examine_status", hyDriverDTO.getExamineStatus());
            }
        }

        if (StringUtils.isNotBlank(hyDriverDTO.getExamineType())) {
            queryWrapper.eq("d.examine_type", hyDriverDTO.getExamineType());
        }

        queryWrapper.orderByDesc("u.create_time");

        Page<HyDriverDTO> page = new Page<HyDriverDTO>(1, 65000);
        IPage<HyDriverDTO> pageList = hyDriverService.pageList(page, queryWrapper, customerId);

        List<HyDriver> exportList = new ArrayList<>();
        String domianURL = request.getParameter("domianURL") + "/";
        for (HyDriverDTO dto : pageList.getRecords()) {

            HyDriverDTO driver = new HyDriverDTO();
            BeanUtil.copyProperties(dto, driver, true);

            String idcardImg = driver.getIdcardImg();
            if (StringUtils.isNotEmpty(idcardImg)) {
                driver.setIdcardImg(domianURL + idcardImg);
            }

            String idcardImgBack = driver.getIdcardImgBack();
            if (StringUtils.isNotEmpty(idcardImgBack)) {
                driver.setIdcardImgBack(domianURL + idcardImgBack);
            }

            String driverImg = driver.getDriverImg();
            if (StringUtils.isNotEmpty(driverImg)) {
                driver.setDriverImg(domianURL + driverImg);
            }

            String driverImg2 = driver.getDriverImg2();
            if (StringUtils.isNotEmpty(driverImg2)) {
                driver.setDriverImg2(domianURL + driverImg2);
            }

            exportList.add(driver);
        }

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "司机列表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, HyDriverDTO.class);
        ExportParams exportParams = new ExportParams();
        exportParams.setAddIndex(true);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);

        return mv;
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls2")
    public ModelAndView exportXls2() {
        ModelAndView mv = new ModelAndView("平台");
        Object failUploadFwfList = redisUtil.get("failUploadFwfList");
        Map map = new HashMap();
        map.put("123", "");
        mv.addAllObjects(map);

        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @RequiresPermissions("sys:driver:importExcel")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HyDriver.class);
    }

    @AutoLog(value = "司机审核")
    @ApiOperation(value = "司机审核", notes = "司机审核")
    @PutMapping(value = "/examine")
    @RequiresPermissions("sys:driver:examine")
    public Result<?> examine(@RequestBody HyDriver hyDriver) {

        if (!ExamineStatusEnum.isValid(hyDriver.getExamineStatus())) {
            return Result.error("审核状态不正确!");
        }

        //Modified at 2024-05-22 司机审核时只update指定字段
        this.hyDriverService.update(new LambdaUpdateWrapper<HyDriver>()
                .eq(HyDriver::getId, hyDriver.getId())
                .set(HyDriver::getExamineStatus, hyDriver.getExamineStatus())
                .set(HyDriver::getExamineType, "1")
                .set(HyDriver::getExamineDate, new Date())
                .set(HyDriver::getExaminRemark, hyDriver.getExaminRemark())
        );


//		 HyDriver hyDriverDb = hyDriverService.getById(hyDriver.getId());
//		 LoginUser loginUser = UserUtil.getLoginUser();
//		 HyWarningMessage hyWarningMessage = new HyWarningMessage();
//		 hyWarningMessage.setObjectId(hyDriver.getId());
//		 hyWarningMessage.setUserId(hyDriverDb.getUserId());
//		 hyWarningMessage.setMessageType(MessageTypeEnum.MESSAGE_TYPE_SJSH.getCode());
//		 hyWarningMessage.setMessageContent(
//				 "司机:"+hyDriverDb.getDriverName()+" 已审核通过 !"
//		 );
//		 hyWarningMessage.setCreateBy(loginUser.getUsername());
//		 hyWarningMessage.setCreateTime(new Date());
//		 hyWarningMessageService.saveWarningMessage(hyWarningMessage);
        return Result.OK("审核成功!");
    }

//    @AutoLog(value = "中交中间件司机上报")
//    @ApiOperation(value = "中交中间件司机上报", notes = "中交中间件司机上报")
//    @PutMapping(value = "/zjupload")
//    public Result<?> zjupload(@RequestBody HyDriver hyDriver) {
//        return this.zjiaoReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "天津司机上报")
//    @ApiOperation(value = "天津司机上报", notes = "天津司机上报")
//    @PutMapping(value = "/upload")
//    public Result<?> upload(@RequestBody HyDriver hyDriver) {
//        return this.tjJgReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "河北司机上报")
//    @ApiOperation(value = "河北司机上报", notes = "河北司机上报")
//    @PutMapping(value = "/hbupload")
//    @RequiresPermissions("sys:driver:hbupload")
//    public Result<?> hbupload(@RequestBody HyDriver hyDriver) {
//        return hbReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "河南司机上报")
//    @ApiOperation(value = "河南司机上报", notes = "河南司机上报")
//    @PutMapping(value = "/hnupload")
//    public Result<?> hnupload(@RequestBody HyDriver hyDriver) {
//        return this.henanReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "辽宁司机上报")
//    @ApiOperation(value = "辽宁司机上报", notes = "辽宁司机上报")
//    @PutMapping(value = "/lnupload")
//    @RequiresPermissions("sys:driver:lnupload")
//    public Result<?> lnupload(@RequestBody HyDriver hyDriver) {
//        return liaoNingReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "云南司机上报")
//    @ApiOperation(value = "云南司机上报", notes = "云南司机上报")
//    @PutMapping(value = "/ynupload")
//    @RequiresPermissions("sys:driver:ynupload")
//    public Result<?> ynupload(@RequestBody HyDriver hyDriver) {
//        return this.yunnanReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "陕西司机上报")
//    @ApiOperation(value = "陕西司机上报", notes = "陕西司机上报")
//    @PutMapping(value = "/sxupload")
//    public Result<?> sxupload(@RequestBody HyDriver hyDriver) {
//        return this.shaanxiReportService.reportDriver(hyDriver.getId(), "1000");
//    }

    @AutoLog(value = "鄂尔多斯市司机上报")
    @ApiOperation(value = "鄂尔多斯市司机上报", notes = "鄂尔多斯市司机上报")
    @PutMapping(value = "/ordosupload")
    public Result<?> ordosupload(@RequestBody HyDriver hyDriver) {
        return this.ordosReportService.reportDriver(hyDriver.getId(), "3000");
    }

    @AutoLog(value = "司机上报")
    @ApiOperation(value = "司机上报", notes = "司机上报")
    @PutMapping(value = "/uploadDriver")
    public Result<?> uploadDriver(@RequestBody HyDriverDTO hyDriver) {

        if (StrUtil.isEmpty(hyDriver.getCompanyId())) {
            return Result.error("未选择分公司");
        }

        //申报公司
        HyCompanyConfig companyConfig = companyConfigService.getOne(new QueryWrapper<HyCompanyConfig>()
                .eq("company_id", hyDriver.getCompanyId()
        ));

        if (companyConfig == null) {
            throw new JeecgBootException("上报公司配置信息不存在");
        }

        log.warn("按公司上报司机，{}", JSONUtil.toJsonStr(companyConfig));
        //hyShippingNoteDb.setCompanyId(hyShippingNoteDb.getCompanyId());
        //在getReport中做判断 如果report==null，抛异常
        IReportService reportService = ReportServiceFactory.getReport(companyConfig.getReportPlatformType());
        reportService.checkReport();
        reportService.setReportInfo(companyConfig);
        return reportService.reportDriver(hyDriver.getId(), hyDriver.getCompanyId());
    }

//    @AutoLog(value = "江苏司机上报")
//    @ApiOperation(value = "江苏司机上报", notes = "江苏司机上报")
//    @PutMapping(value = "/jsupload")
//    public Result<?> jsupload(@RequestBody HyDriver hyDriver) {
//        return jsuReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "江苏V2司机上报")
//    @ApiOperation(value = "江苏V2司机上报", notes = "江苏V2司机上报")
//    @PutMapping(value = "/jsv2upload")
//    public Result<?> jsv2upload(@RequestBody HyDriver hyDriver) {
//        return this.jsuV2ReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "新疆司机上报")
//    @ApiOperation(value = "新疆司机上报", notes = "新疆司机上报")
//    @PutMapping(value = "/xjupload")
//    public Result<?> xjupload(@RequestBody HyDriver hyDriver) {
//        return this.xjReportService.uploadDriver(hyDriver.getId());
//    }
//
//
//    @AutoLog(value = "宁夏司机上报")
//    @ApiOperation(value = "宁夏司机上报", notes = "宁夏司机上报")
//    @PutMapping(value = "/nxupload")
//    public Result<?> nxupload(@RequestBody HyDriver hyDriver) {
//        return this.nxReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "内蒙古司机上报")
//    @ApiOperation(value = "内蒙古司机上报", notes = "内蒙古司机上报")
//    @PutMapping(value = "/nmgupload")
//    public Result<?> nmgupload(@RequestBody HyDriver hyDriver) {
//        return this.nmgReportService.uploadDriver(hyDriver.getId());
//    }

    @AutoLog(value = "淮北司机上报")
    @ApiOperation(value = "淮北司机上报", notes = "淮北司机上报")
    @PutMapping(value = "/huaibeiupload")
    public Result<?> huaibeiupload(@RequestBody HyDriver hyDriver) {
        return this.huaibeiReportService.uploadDriver(hyDriver.getId());
    }

    @AutoLog(value = "园区司机上报")
    @ApiOperation(value = "园区司机上报", notes = "园区司机上报")
    @PutMapping(value = "/yqupload")
    public Result<?> yqupload(@RequestBody HyDriver hyDriver) {
        return this.yuanqvReportService.uploadDriver(hyDriver.getId());
    }

//    @AutoLog(value = "江西司机上报")
//    @ApiOperation(value = "江西司机上报", notes = "江西司机上报")
//    @PutMapping(value = "/jxupload")
//    public Result<?> jxupload(@RequestBody HyDriver hyDriver) {
//        return this.jxiReportService.uploadDriver(hyDriver.getId());
//    }
//
//    @AutoLog(value = "重庆司机上报")
//    @ApiOperation(value = "重庆司机上报", notes = "重庆司机上报")
//    @PutMapping(value = "/cqupload")
//    public Result<?> cqupload(@RequestBody HyDriver hyDriver) {
//        return this.cqReportService.uploadDriver(hyDriver.getId());
//    }

    @AutoLog(value = "道达上报")
    @ApiOperation(value = "道达上报", notes = "道达上报")
    @PutMapping(value = "/daodaUpload")
    public Result<?> daodaUpload(@RequestBody HyDriver hyDriver) {
        return hyDriverService.uploadDaoda(hyDriver) ? Result.OK("上报成功!") : Result.error("上报失败!");
    }

    @GetMapping(value = "/testCheckDriver")
    public Result<?> testCheckDriver() {
        String re = hyDriverService.testCheckDriver();
        return Result.OK(re);
    }

    //上传服务方（车主）信息
    @PostMapping(value = "/tjTaxUpload")
    public Result<?> tjTaxUpload(@RequestBody HyDriver hyDriver) {
        ApiBaseResDTO apiBaseResDTO = hyDriverService.tjTaxUpload(hyDriver);
        int resCode = StringUtils.isNotEmpty(apiBaseResDTO.getCode()) ? Integer.valueOf(apiBaseResDTO.getCode()) : 0;
        if (resCode >= 100 && resCode < 200) {
            return Result.OK("上报成功！");
        } else {
            return Result.error("上报失败！" + apiBaseResDTO.getDesc());
        }
    }

    @AutoLog(value = "辽宁税务上报司机信息")
    @ApiOperation(value = "辽宁税务上报司机信息", notes = "辽宁税务上报司机信息")
    @PutMapping(value = "/lnTaxUploadDriver")
    public Result<?> lnTaxUploadDriver(@RequestBody HyDriver hyDriver) {
        return hyDriverService.lnTaxUploadDriver(hyDriver);
    }


    @AutoLog(value = "辽宁税务更新司机信息")
    @PutMapping(value = "/updatelnTaxUploadDriver")
    public Result<?> updatelnTaxUploadDriver(@RequestBody HyDriver hyDriver) {
        return hyDriverService.updatelnTaxUploadDriver(hyDriver);
    }


    @AutoLog(value = "辽宁税务查询司机实名制")
    @ApiOperation(value = "辽宁税务查询司机实名制", notes = "辽宁税务查询司机实名制")
    @PutMapping(value = "/lnTaxDriverAuth")
    public Result<?> lnTaxDriverAuth(@RequestBody HyDriver hyDriver) {
        HyDriver driver = hyDriverService.getDriverById(hyDriver.getId());
        if (null == driver) {
            return Result.error("司机信息不存在");
        }

        return this.shippingNoteApiAlct56Service.queryDriverForAuth(driver);
    }

    @AutoLog(value = "辽宁司机税登")
    @ApiOperation(value = "辽宁税务上报司机信息", notes = "辽宁税务上报司机信息")
    @PutMapping(value = "/lnTaxedDriver")
    public Result<?> lnTaxedDriver(@RequestBody JSONObject jsonObject) {
        String ids = jsonObject.getString("ids");
        if (StrUtil.isEmpty(ids)) {
            return Result.error("请选择司机");
        }

        return hyDriverService.lnTaxedDriver(ids);
    }

    @AutoLog(value = "辽宁税务上报司机照片")
    @ApiOperation(value = "辽宁税务上报司机照片", notes = "辽宁税务上报司机照片")
    @PutMapping(value = "/lnTaxUploadDriverImg")
    public Result<?> lnTaxUploadDriverImg(@RequestBody JSONObject jsonObject) {
        JSONObject vehicleO = jsonObject.getJSONObject("driver");
        HyDriver hyDriver = vehicleO.toJavaObject(HyDriver.class);
        int index = jsonObject.getInteger("index");
        return hyDriverService.lnTaxUploadDriverImg(hyDriver, index);
    }

    @AutoLog(value = "辽宁税务上报司机所有信息")
    @ApiOperation(value = "辽宁税务上报司机所有信息", notes = "辽宁税务上报司机所有信息")
    @PutMapping(value = "/lnTaxUploadDriverAll")
    public Result<?> lnTaxUploadDriverAll(@RequestBody HyDriver hyDriver) {
        return hyDriverService.lnTaxUploadDriverAll(hyDriver);
    }


    //快货运上传司机信息
    @PostMapping(value = "/tosUploadDriver")
    public Result<?> tosUploadDriver(@RequestBody HyDriver hyDriver) {
        return hyDriverService.tosUploadDriver(hyDriver);
    }

    //快货运上传承运人信息
    @PostMapping(value = "/tosUploadCarrier")
    public Result<?> tosUploadCarrier(@RequestBody HyDriver hyDriver) {
        return hyDriverService.tosUploadCarrier(hyDriver);

    }


	/*//导入Excal表
	//后台接口，图片上传请求默认为 post 请求，
	// 通过 MultipartFile 类型接收上传的文件，
	// 注意这里的 @RequestParam("file") 括号里的参数要和前端上传的名称一致，不一致的情况就是后台接收不到参数
	@PostMapping(value = "/import")
	public Boolean importExcelData(@RequestParam("file") MultipartFile file) {
		return hyDriverService.importExcelData(file);
	}*/


    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public Result<?> all(HttpServletRequest request) {
        QueryWrapper<HyDriver> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("examine_status", ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
        queryWrapper.eq("del_flag", "0");
        queryWrapper.orderByDesc("create_time");
        return Result.ok(hyDriverService.list(queryWrapper));
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/importDriver", method = RequestMethod.POST)
//	@RequiresPermissions("sys:driver:importExcel")
    public Result<?> importDriver(HttpServletRequest request) throws InterruptedException {
        List<ImportHyDriverDTO> list = ExcelUtil.importExcel(request, ImportHyDriverDTO.class);
        if (CollectionUtils.isEmpty(list)) {
            return Result.error("导入数据不能为空！");
        }

        this.checkData(list);
        //身份证号查询司机是否存在
        List<String> drivingLicenses = list.stream().map(
                item -> item.getDrivingLicense().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());


        int section = 10;
        List<HyDriver> driverList = new LinkedList<>();
        for (int index = 0, end = 0; index < drivingLicenses.size(); index = end) {
            end = (end + section) <= drivingLicenses.size() ? end + section : drivingLicenses.size();
            if (index < end) {
                QueryWrapper<HyDriver> querydriverWrapper = new QueryWrapper();
                querydriverWrapper.in("idcard", drivingLicenses.subList(index, end));
                driverList.addAll(hyDriverService.list(querydriverWrapper));
            }
        }

        if (driverList.size() > 0) {
            List<String> dbIdcards = driverList.stream().map(
                    item -> item.getIdcard()
            ).collect(Collectors.toList());

            String filterIdcards = drivingLicenses.stream()
                    .filter(item -> dbIdcards.contains(item))
                    .collect(Collectors.joining(",", "(", ")"));

            return Result.error(filterIdcards + "司机数据信息已存在");
        }


        //查询用户查询手机号是否存在
        List<String> telephones = list.stream().map(
                item -> item.getTelephone().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());

        int usection = 10;
        List<SysUser> sysUserList = new LinkedList<>();
        for (int index = 0, end = 0; index < telephones.size(); index = end) {
            end = (end + usection) <= telephones.size() ? end + usection : telephones.size();
            if (index < end) {
                QueryWrapper<SysUser> queryUserWrapper = new QueryWrapper();
                queryUserWrapper.in("phone", telephones.subList(index, end));
                sysUserList.addAll(userService.list(queryUserWrapper));
            }
        }

        if (sysUserList.size() > 0) {
            List<String> dbPhones = sysUserList.stream().map(
                    item -> item.getPhone()
            ).collect(Collectors.toList());

            String filterPhones = telephones.stream()
                    .filter(item -> dbPhones.contains(item))
                    .collect(Collectors.joining(",", "(", ")"));

            return Result.error(filterPhones + "用户手机号数据信息已存在");
        }

        //Added at 2023-07-18 for 特殊司机导入模板可以配置要上传的图片URL
        //根据图片URL下载图片
        int index = 0;
        for (ImportHyDriverDTO dto : list) {
            String serverFolderPath = this.uploadpath + File.separator + "driver";

            //身份证正面
            if (StrUtil.isNotEmpty(dto.getIdcardImg())) {
                //String idcardImgPath = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getIdcardImg(), serverFolderPath, dto.getDriverName());
                String idcardImgPath = postDownloadEvent(dto.getIdcardImg(), serverFolderPath, dto.getDriverName());
                //覆盖导入的长地址，启用网货平台对应的短地址,前面拼接driver目录
                dto.setIdcardImg("driver/" + idcardImgPath);
                Thread.sleep(300);
            }

            //身份证反面
            if (StrUtil.isNotEmpty(dto.getIdcardImgBack())) {
                //String idcardImgBackPath = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getIdcardImgBack(), serverFolderPath, dto.getDriverName());
                String idcardImgBackPath = postDownloadEvent(dto.getIdcardImgBack(), serverFolderPath, dto.getDriverName());
                dto.setIdcardImgBack("driver/" + idcardImgBackPath);
            }

            //驾驶证主页
            if (StrUtil.isNotEmpty(dto.getDriverImg())) {
                //String driverImgPath = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getDriverImg(), serverFolderPath, dto.getDriverName());

                String driverImgPath = postDownloadEvent(dto.getDriverImg(), serverFolderPath, dto.getDriverName());
                dto.setDriverImg("driver/" + driverImgPath);
                Thread.sleep(300);
            }

            //驾驶证副页
            if (StrUtil.isNotEmpty(dto.getDriverImg2())) {
                //String driverImgBackPath = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getDriverImg2(), serverFolderPath, dto.getDriverName());

                String driverImgBackPath = postDownloadEvent(dto.getDriverImg2(), serverFolderPath, dto.getDriverName());
                dto.setDriverImg2("driver/" + driverImgBackPath);
            }

            //从业资格证主页
            if (StrUtil.isNotEmpty(dto.getQualificationImg())) {
                //String qualificaitionImgPath = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getQualificationImg(), serverFolderPath, dto.getDriverName());

                String qualificaitionImgPath = postDownloadEvent(dto.getQualificationImg(), serverFolderPath, dto.getDriverName());
                dto.setQualificationImg("driver/" + qualificaitionImgPath);
            }

            log.info("正在下载{}图片 {}/{}", dto.getDriverName(), index, list.size());
            index++;
        }

        hyDriverService.saveBatchDriver(list);
        return Result.OK("文件导入成功！数据行数：" + list.size());
    }


    private String postDownloadEvent(String downloadUrl, String serverFolderPath, String serverFolderName) {

        this.applicationEventPublisher.publishEvent(PicDownloadEvent.builder()
                .type("driver")
                .downloadUrl(downloadUrl)
                .serverFolderPath(serverFolderPath)
                .serverFolderName(serverFolderName)
                .build()
        );

        int lastIndex = downloadUrl.lastIndexOf('/');
        String filename = downloadUrl.substring(lastIndex);

        return serverFolderName + File.separator + filename;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/importDriver2", method = RequestMethod.POST)
//	@RequiresPermissions("sys:driver:importExcel")
    public Result<?> importDriver2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<ImportFWFHyDriverDTO> list = ExcelUtil.importExcel(request, ImportFWFHyDriverDTO.class);
        if (CollectionUtils.isEmpty(list)) {
            return Result.error("导入数据不能为空！");
        }

        this.checkData2(list);
        //身份证号查询司机是否存在
        List<String> drivingLicenses = list.stream().map(
                item -> item.getFwfsfzjhm().trim()
        ).distinct().filter(Objects::nonNull).collect(Collectors.toList());


        int section = 10;
        List<HyDriver> driverList = new LinkedList<>();
        for (int index = 0, end = 0; index < drivingLicenses.size(); index = end) {
            end = (end + section) <= drivingLicenses.size() ? end + section : drivingLicenses.size();
            if (index < end) {
                QueryWrapper<HyDriver> querydriverWrapper = new QueryWrapper();
                querydriverWrapper.in("idcard", drivingLicenses.subList(index, end));
                driverList.addAll(hyDriverService.list(querydriverWrapper));
            }
        }


        //空间换时间 降低时间复杂度
        Map<String, ImportFWFHyDriverDTO> tempMap = new HashMap<>();
        for (ImportFWFHyDriverDTO str : list) {
            tempMap.put(str.getFwfsfzjhm(), str);
        }
        for (HyDriver driver : driverList) {
            if (tempMap.containsKey(driver.getIdcard())) {
                driver.setFwfuuid(tempMap.get(driver.getIdcard()).getFWFUUID());
                list.remove(tempMap.get(driver.getIdcard()));
            }
        }
        Integer failCount = 0;
        failCount = list.size();

//		redisUtil.set("failUploadFwfList",list);
        hyDriverService.updateBatchById(driverList);

        if (failCount == 0) {
            return Result.ok("文件导入成功！数据条数：" + driverList.size() + "条");
        }


        ExportParams exportParams = new ExportParams(null, "title");

        exportParams.setAddIndex(false);
//		exportParams.setCreateHeadRows(false);

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, ImportFWFHyDriverDTO.class, list);

        response.setHeader("Access-Control-Expose-Headers", "content-disposition");

        response.setHeader("content-disposition", "attachment;filename="
                + URLEncoder.encode("未匹配成功的数据.xlsx", "UTF-8")
                + ";"
                + URLEncoder.encode("文件导入成功的数据条数" + driverList.size() + "条。" + "未匹配成功的数据条数" + failCount + "条。", "UTF-8"));
        ServletOutputStream out = response.getOutputStream();
        sheets.write(out);
        out.flush();
        return Result.error(-99, "12312312");

    }


    private void checkData2(List<ImportFWFHyDriverDTO> list) {
        int i = 2;
        for (ImportFWFHyDriverDTO importHyDriverDTO : list) {
            String key = String.valueOf(i);

            if (StringUtils.isBlank(importHyDriverDTO.getFWFUUID())) {
                throw new JeecgBootException("第" + key + "行uuid不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importHyDriverDTO.getFWFXM())) {
                throw new JeecgBootException("第" + key + "行姓名不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importHyDriverDTO.getFwfsfzjhm())) {
                throw new JeecgBootException("第" + key + "行身份证号不能为空,请先补充信息");
            }

            i++;
        }


    }

    private void checkData(List<ImportHyDriverDTO> list) {
        int i = 2;
        for (ImportHyDriverDTO importHyDriverDTO : list) {
            String key = String.valueOf(i);

            if (StringUtils.isBlank(importHyDriverDTO.getDriverName())) {
                throw new JeecgBootException("第" + key + "行司机名称不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importHyDriverDTO.getDrivingLicense())) {
                throw new JeecgBootException("第" + key + "行身份证号不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importHyDriverDTO.getVehicleClass())) {
                throw new JeecgBootException("第" + key + "行准驾车型不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importHyDriverDTO.getIssuingOrganizations())) {
                throw new JeecgBootException("第" + key + "行驾驶证发证机关不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importHyDriverDTO.getQualificationCertificate())) {
                throw new JeecgBootException("第" + key + "行驾驶员从业资格证号不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importHyDriverDTO.getTelephone())) {
                throw new JeecgBootException("第" + key + "行手机号码不能为空,请先补充信息");
            }
            Date validPeriodFrom = DateUtils.str2Date(importHyDriverDTO.getValidPeriodFrom(), DateUtils.date_sdf.get());
            Date validPeriodTo = DateUtils.str2Date(importHyDriverDTO.getValidPeriodTo(), DateUtils.date_sdf.get());

            if (validPeriodFrom == null) {
                throw new JeecgBootException("第" + key + "行驾驶证有效期自不正确,应为日期文本格式");
            }
            if (validPeriodTo == null) {
                throw new JeecgBootException("第" + key + "行驾驶证有效期至不正确,应为日期文本格式");
            }
            i++;
        }


    }

    @ApiOperation(value = "司机管理-分页列表查询", notes = "司机管理-分页列表查询")
    @GetMapping(value = "/getDriverUserList")
    @RequiresRoles(value={"admin","admin-1"})
    public Result<?> getDriverUserList(DriverUserDTO driverUserDTO,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<DriverUserDTO> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("u.`status`", 1);
        queryWrapper.eq("u.`u_type`", "4");

        if (StringUtils.isNotEmpty(driverUserDTO.getRealname())) {
            queryWrapper.like("u.realname", driverUserDTO.getRealname());
        }
        if (StringUtils.isNotEmpty(driverUserDTO.getPhone())) {
            queryWrapper.like("u.phone", driverUserDTO.getPhone());
        }

        if (StringUtils.isNotEmpty(driverUserDTO.getDriverName())) {
            queryWrapper.like("d.driver_name", driverUserDTO.getDriverName());
        }

        if (StringUtils.isNotEmpty(driverUserDTO.getIdcard())) {
            queryWrapper.like("d.idcard", driverUserDTO.getIdcard());
        }

        if (StringUtils.isNotEmpty(driverUserDTO.getTelephone())) {
            queryWrapper.like("d.telephone", driverUserDTO.getTelephone());
        }

        if (StringUtils.isNotEmpty(driverUserDTO.getVehicleNumber())) {
            queryWrapper.like("v.vehicle_number", driverUserDTO.getVehicleNumber());
        }

        if (StringUtils.isNotEmpty(driverUserDTO.getCreateTime_begin())) {
            queryWrapper.ge("u.create_time", driverUserDTO.getCreateTime_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(driverUserDTO.getCreateTime_end())) {
            queryWrapper.le("u.create_time", driverUserDTO.getCreateTime_end() + " 23:59:59");
        }
        //queryWrapper.isNull("dv.iz_used");

        if (StringUtils.isNotEmpty(driverUserDTO.getIzUsed())) {
            if ("-1".equals(driverUserDTO.getIzUsed())) {
                queryWrapper.isNull("dv.iz_used");
            } else {
                queryWrapper.eq("dv.iz_used", driverUserDTO.getIzUsed());
            }

        }

        queryWrapper.orderByDesc("u.create_time");

        Page<DriverUserDTO> page = new Page<DriverUserDTO>(pageNo, pageSize);
        IPage<DriverUserDTO> pageList = hyDriverService.getDriverUserPageList(page, queryWrapper);

        for (DriverUserDTO dto : pageList.getRecords()) {
            dto.setTelephone(DataMaskingUtil.phoneMasking(dto.getTelephone()));
            dto.setPhone(DataMaskingUtil.phoneMasking(dto.getPhone()));
            dto.setIdcard(DataMaskingUtil.idcardMasking(dto.getIdcard()));
            dto.setVehicleId(null);
        }

        return Result.OK(pageList);
    }

    /**
     * 获取待审信息
     *
     * @return
     */
    @GetMapping(value = "/getDsXx")
    public Result<?> getDsDriver() {
        int sijiCount = hyDriverService.getDsDriverCount(userUtil.getCustomerById());
        int cheCount = hyVehicleService.getDsvehicleCount(userUtil.getCustomerById());
        int huozhuCount = 0;
        if (userUtil.isSys()) {
            huozhuCount = hyCustomerService.count(new QueryWrapper<HyCustomer>()
                    .eq("examine_status", 1)
            );
        }

        int yuejieZhangQi = hyOrderService.selectOrderZhangQi("1", userUtil.getCustomerById());
        int pijieZhangQi = hyOrderService.selectOrderZhangQi("2", userUtil.getCustomerById());
        int tangjieZhangQi = hyOrderService.selectOrderZhangQi("3", userUtil.getCustomerById());

        //垫付待还款账期提醒 1个月期限  查询创建日期是一个月以后的并且st ==0
        int dianfuZq = hyPlatformCostService.getZqCount(userUtil.getCustomerById());


        Map map = new HashMap();
        map.put("sijiCount", sijiCount);
        map.put("cheCount", cheCount);
        map.put("huozhuCount", huozhuCount);
        map.put("yuejieZhangQi", yuejieZhangQi);
        map.put("pijieZhangQi", pijieZhangQi);
        map.put("tangjieZhangQi", tangjieZhangQi);
        map.put("dianfuZq", dianfuZq);
        return Result.OK(map);
    }

    /**
     * 车辆挂靠声明添加司机签章
     */
    @AutoLog(value = "APP电子签章-司机签章")
    @ApiOperation(value = "APP电子签章-司机签章", notes = "APP电子签章-添加司机签章")
    @PostMapping(value = "/addSignet")
    public Result<?> addSignet(@RequestBody JSONObject jsonObject) {
        String signetBase64 = jsonObject.getString("signetBase64");
        String driverId = jsonObject.getString("driverId");
        //log.debug("[车辆挂靠声明添加司机签章] 签章base64：{}", signetBase64);

        HyDriver driver = hyDriverService.getById(driverId);
        if (driver == null) {
            return Result.error("司机信息获取错误！");
        }
        if (signetBase64 == null || StringUtils.isEmpty(signetBase64)) {
            return Result.error("签名图片Base64码错误！");
        }
        String signetPath = "documents" + File.separator + DateUtils.getDate("yyyyMMdd") + File.separator + "司机签名_" + DateUtils.getDate("yyyyMMddHHmmss") + ".png";
        String signetWholePath = uploadpath + File.separator + signetPath;
        log.debug("[车辆挂靠声明添加司机签章]signetPath：{}", signetPath);
        boolean toImg = ImageBase64Util.base64StringToImage(signetBase64, signetWholePath);
        if (toImg == false) {
            return Result.error("base64转图片失败！");
        } else {
            return Result.OK(signetPath);
        }
    }


    /**
     * 全图车辆展示
     */
    @AutoLog(value = "全图车辆展示-全图车辆展示")
    @ApiOperation(value = "全图车辆展示-全图车辆展示", notes = "全图车辆展示-全图车辆展示")
    @GetMapping(value = "/mapOverView")
    public Result<?> mapOverView() {

        String res = openApiService.mapOverView();
        JSONObject jsonObject = JSONObject.parseObject(res);
        String result = jsonObject.get("result").toString();
        return Result.OK(result);
    }
   /* *//**
     * 获取AipOcr文字识别资源
     * @param savePath
     * @param upType
     * @param side 如果upType是身份证类型需要传该字段 side:front正面 ;back背面
     * @return
     *//*
    @SneakyThrows
    private JSONObject getAipOcrResources(String savePath ,String upType,String side)  {
//        Objects.requireNonNull(savePath);
//        Objects.requireNonNull(upType);
        if(StringUtils.isEmpty(savePath) || StringUtils.isEmpty(upType)){
            return new JSONObject();
        }

        String file = uploadpath+File.separator+savePath;


        String jsonString = "";
        switch (upType){
            case UpDocumentTypeConstant.DOCUMENT_TYPE_IDCARD:
                if(StringUtils.isNotEmpty(side)){
                    side = side.equals("front") ? "face": "back";
                    jsonString =  aliyunOcrService.ocrIdcard(file,side);
//
                }
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_BANKCARD:
//                    jsonString =  aipOcrService.bankCard(file);
                String httpUrl = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_BANKCARD);
                jsonString=  huaweiOcrService.getInfoByAKSK(file , httpUrl, "");
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_DRIVINGLICENSE:
                if(StringUtils.isNotEmpty(side)) {
                    String httpUri = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_DRIVER_LICENSE);
                    jsonString=  huaweiOcrService.getInfoByAKSK(file , httpUri, side);
//                    side = side.equals("front") ? "face" : "back";
//                    jsonString = aliyunOcrService.ocrDriver(file, side);
                }
                //jsonString =  aipOcrService.drivingLicense(file);
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_VEHICLELICENSE:
                if(StringUtils.isNotEmpty(side)) {
                    String httpUri = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_VEHICLE_LICENSE);
                    jsonString=  huaweiOcrService.getInfoByAKSK(file, httpUri, side);
//                    side = side.equals("front") ? "face" : "back";
//                    jsonString = aliyunOcrService.ocrVehicle(file, side);
                    // jsonString = aipOcrService.vehicleLicense(file, side);
                }
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_PLATELICENSE:
                jsonString =  aipOcrService.plateLicense(file);
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_BUSINESSLICENSE:
//                jsonString =  aipOcrService.businessLicense(file);
                String httpUrl1 = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_BUSINESS_LICENSE);
                jsonString=  huaweiOcrService.getInfoByAKSK(file , httpUrl1, "");
                break;
            case UpDocumentTypeConstant.DOCUMENT_TYPE_TRANSPORTATION_LICENSE:
                String httpUri = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_TRANSPORTATION_LICENSE);
                jsonString=  huaweiOcrService.getInfoByAKSK( file , httpUri, "");
                break;
            case UpDocumentTypeConstant.QUALIFICATIONIMG:
                String httpUri1 = huaweiOcrService.getURL(HuaweiOcrConstant.TRANSPORTATION_QUALIFICATION_CERTIFICATE);
                jsonString=  huaweiOcrService.getInfoByAKSK( file , httpUri1, "");
                break;
            default:
                jsonString =  aipOcrService.basicAccurateGeneral(file);
        }
        return StringUtils.isNotEmpty(jsonString)  ? JSONObject.parseObject(jsonString) : new JSONObject();
    }
    *//**
     * 压缩图片
     * @param bizPath
     * @param file
     * @return
     * @throws IOException
     *//*
    private String getCompressPic(String bizPath, MultipartFile file) throws IOException {
//        int fileSize = (int)(file.getSize() / 1024)+1;
//        float quality = 1F;
//        if(fileSize <= 600){
//            quality = 0.8F;
//        }else if(fileSize <= 800){
//            quality = 0.6F;
//        }else if(fileSize <= 1000){
//            quality = 0.4F;
//        }else{
//            quality = 0.25F;
//        }

//        byte[] imgBytes = ImageCompressUtil.compressPicForScale(file.getBytes(), quality );
//        String imgBase64 =   Base64.encodeBase64String(imgBytes);

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            String savePathTemp = this.uploadLocal(file,bizPath);
            String imgBase64 = ImageUtil.compressImgToBase64(uploadpath + File.separator +savePathTemp, 1024, 768, 1024 * 1024);

            // Base64解码
            byte[] b = decoder.decodeBuffer(imgBase64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            //将byte转换为文件
            // 生成图片路径和文件名
            String ctxPath = uploadpath;
            String fileName = null;
            File files = new File(ctxPath + File.separator + bizPath + File.separator );
            if (!files.exists()) {
                files.mkdirs();// 创建文件根目录
            }

            String orgName = file.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);

            if(orgName.indexOf(".") != -1){
                fileName = "compress_"+orgName.substring(0, orgName.lastIndexOf(".")) + "_" + imgName  + orgName.substring(orgName.indexOf("."));
            }else{
                fileName = "compress_" +  imgName  + orgName;
            }
            String savePath = files.getPath() + File.separator + fileName;

            FileOutputStream out = new FileOutputStream(savePath);
            out.write(b);
            out.flush();
            out.close();

            String dbpath = null;
            if(oConvertUtils.isNotEmpty(bizPath)){
                dbpath = bizPath + File.separator + fileName;
            }else{
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
        return StringUtils.EMPTY;
    }
    *//**
     * 本地文件上传
     * @param mf 文件
     * @param bizPath  自定义路径
     * @return
     *//*
    private String uploadLocal(MultipartFile mf,String bizPath){
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator );
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            imgName = DateUtils.dateToStringDateTime(new Date());
            if(orgName.indexOf(".") != -1){
                fileName = "original_"+orgName.substring(0, orgName.lastIndexOf(".")) + "_" + imgName  + orgName.substring(orgName.indexOf("."));
            }else{
                fileName = "original_" + imgName  + orgName;
            }

            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if(oConvertUtils.isNotEmpty(bizPath)){
                dbpath = bizPath + File.separator + fileName;
            }else{
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    private  MultipartFile convertToMultipartFile(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file",
                file.getName(), "text/plain", input);
        return multipartFile;
    }
*/



}
